use ../processed/Census_aggr.dta, clear

// create CL CA RS category
gen CL7 = (CL==7)
gen CL8 = (CL==8)
gen CL9 = (CL>=9)
gen CCA8 = (CCA==8)
gen CCA9 = (CCA==9)
gen CCA10= (CCA>=10)
gen RS7 = (RS==7)
gen RS8 = (RS==8)
gen RS9 = (RS>=9)

gen age_yob = (year-1)-birthyr
tab year [fw=nobs], m
local nobs_csl = r(N)
disp `nobs_csl'

rename bpl statefip
merge m:1 statefip using ../data/region_division_state.dta
drop if _merge==2
assert _merge==3
rename statefip bpl

egen cs = group(birthyr bpl) // cohort*bpl
// FS regression
local iv1 CL7 CL8 CL9
local iv2 CCA8 CCA9 CCA10
local iv3 RS7 RS8 RS9
forvalues j=1/3{
	eststo: reg yschl `iv`j'' i.bpl i.birthyr [pw=wgt], vce(cluster cs)
}
esttab using "../result/first_stage.txt", b(%7.4f) se(%7.4f) order(`iv1' `iv2' `iv3') replace
eststo clear

// additional FS regression results (by cohort and by region)
forvalues j=1/3{
	forvalues y=1960(10)1980{
		eststo: reg yschl `iv`j'' i.bpl i.birthyr if year==`y' [pw=wgt], vce(cluster cs)
	}
	eststo: reg yschl `iv`j'' i.bpl i.birthyr if region==1|region==3 [pw=wgt], vce(cluster cs) // positive weight region
	eststo: reg yschl `iv`j'' i.bpl i.birthyr if region==2|region==4 [pw=wgt], vce(cluster cs) // negative weight region	
}
esttab using "../result/first_stage_add.txt", b(%7.4f) se(%7.4f) order(`iv1' `iv2' `iv3') replace
eststo clear

file open myfile using "../result/first_stage.txt", write append
forvalues l=1/3{
	local iv `iv`l''
	// "weakivtest" command seems to be erratic with cell-aggregated data, so I compute Montiel Olea-Pflueger Effective F based on the formula in the original paper
	qui foreach v in yschl `iv'{
		areg `v' i.birthyr [pw=wgt], a(bpl)
		predict `v'_res, resid
	}
	local iv_r
	foreach v in `iv'{
		local iv_r `iv_r' `v'_res
	}
	corr `iv_r' [aw=wgt], cov
	matrix define V = r(C)
	matrix define A = inv(cholesky(V))
	local iv_n
	local j=0
	foreach v in `iv'{
		local j=`j'+1
		gen `v'_n = 0
		local k=0
		foreach w in `iv'{
			local k=`k'+1
			replace `v'_n = `v'_n + A[`j',`k']*`w'_res
		}
		local iv_n `iv_n' `v'_n
	}
	corr `iv_n' [aw=wgt], cov
	reg yschl_res `iv_n' i.birthyr i.bpl [pw=wgt], vce(cluster cs)
	local sumc = 0
	local sums = 0
	foreach v in `iv_n'{
		local sumc = `sumc' + _b[`v']^2
		local sums = `sums' + _se[`v']^2
	}
	disp %9.5f `sums' %9.5f `sumc' %9.5f `sumc'/`sums'
	drop yschl_res
	if ( `l'==1 ){
		file write myfile "Effective F (Child Labor Laws): " (`sumc'/`sums') _n
	}
	else if (`l'==2 ){
		file write myfile "Effective F (Compulsory Attendance Laws): " (`sumc'/`sums') _n
	}
	else{
		file write myfile "Effective F (Required Years): " (`sumc'/`sums') _n	
	}
}
file close myfile
